package com.zidian.teacher.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.zidian.teacher.R;
import com.zidian.teacher.bean.QuestionnaireListBean;
import com.zidian.teacher.common.BaseFragment;
import com.zidian.teacher.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import com.zidian.teacher.activity.QuestionAddActivity;
import com.zidian.teacher.activity.QuestionDetailActivity;
import com.zidian.teacher.adapter.QuestionnaireAdapter;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.utils.GetUserInfo;

/**
 * Created by Administrator on 2016/9/5 0005.
 */
public class QuestionnaireFragment extends BaseFragment {

    RecyclerView mRecyclerView;
    SwipeRefreshLayout mSwipeRefreshWidget;
    private boolean isLoading;
    private QuestionnaireAdapter adapter;
    private Handler handler = new Handler();
    private List<QuestionnaireListBean.DataBean.ListBean> data = new ArrayList<>();
    private ImageView questionAdd;
    private int startrow = 1;
    private boolean isRefreshing = false;

    @Override
    protected int getLayoutId() {
        return R.layout.tab_fragment_questionnaire;
    }

    public static QuestionnaireFragment newInstance() {
        return new QuestionnaireFragment();
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.list);
        mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        questionAdd = (ImageView) view.findViewById(R.id.question_add);
        initView();
        initData();
    }

    public void initView() {

        mSwipeRefreshWidget.setColorSchemeResources(R.color.colorAccent);

        mSwipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshWidget.setRefreshing(true);
                isRefreshing = true;
            }
        });
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        isRefreshing = true;
                        startrow = 1;
                        getList(startrow + "");
                    }
                }, 2000);

            }
        });

        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        final LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        adapter = new QuestionnaireAdapter(mActivity, data);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");
                    boolean isRefreshing = mSwipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("test", "load more completed");
                                isLoading = false;
                                startrow++;
                                getList(startrow + "");
                            }
                        }, 1000);

                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new QuestionnaireAdapter.OnItemClickListener() {
            //点击传递问卷ID到问卷详情界面
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), QuestionDetailActivity.class);
                //传递问卷ID，标题，学生总数
                intent.putExtra("questionnaireId",data.get(position).getQuestionnaireId());
                intent.putExtra("questionnaireTitle",data.get(position).getQuestionnaireTitle());
                intent.putExtra("studentsNumber",data.get(position).getChooseNumber());
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {


            }
        });

        questionAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(QuestionAddActivity.class);
            }
        });

    }


    public void initData() {
        getList(startrow + "");
    }

    private void getList(String startrow) {
        String loginUrl = Constant.URL_TEACHER + "Questionnaire/selectQuestionnaire";

        Map<String, String> map = new HashMap<>();
        map.put("teacherId", GetUserInfo.getTeacherId(mActivity));
        map.put("token", GetUserInfo.getToken(mActivity));
        map.put("startrow", startrow);
        map.put("pageSize", "10");

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                ToastUtil.showToast(mActivity.getApplication(), "获取信息失败！");
                mSwipeRefreshWidget.setRefreshing(false);
            }

            @Override
            public void onResponse(String response, int id) {
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
                Log.e("E", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(mActivity.getApplication(), jsonObject.getString("message"));
                        isLoading = true;
                        adapter.setMore(false);
                        adapter.notifyDataSetChanged();
                        return;
                    }


                } catch (JSONException e) {


                }
                Gson gson = new Gson();
                QuestionnaireListBean model = gson.fromJson(response, QuestionnaireListBean.class);
                if (model.isSuccess()) {

                    if (model.getData().getList().size() < 10) {
                        isLoading = true;
                        adapter.setMore(false);
                    } else {
                        isLoading = false;
                        adapter.setMore(true);
                    }

                    data.addAll(model.getData().getList());
                    adapter.notifyDataSetChanged();
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
            }
        });
    }


}
